﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace wld_4g_router_test
{
    public class wld_socket_server
    {
		public Socket wld_socket { get; private set; } = null;
        public Socket wld_client { get; set; } = null;
        public byte[] wld_recv_buf { get; set; } = new byte[8 * 1024 * 1024];
        public delegate void wld_client_connected_cb(string msg);
        public wld_client_connected_cb wld_Client_Connected;
        /// <summary>
        /// 发送数据到客户端
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool SendToClient(byte[] data)
        {
            try
            {
                if (wld_socket is null || wld_client is null || !wld_client.Connected) return false;
                int size = wld_client.Send(data);

                return size == data.Length;
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
            return false;
        }
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void StartListen(string ip, int port)
        {
			try
			{
				wld_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				IPAddress address = IPAddress.Parse(ip);
				IPEndPoint endPoint = new IPEndPoint(address, port);
				wld_socket.Bind(endPoint);
				wld_socket.Listen(2);

				Thread thread = new Thread(ListtenClinetConnect);
				thread.Start();
			}
			catch (Exception err)
			{
				Console.WriteLine(err);
			}
        }
        /// <summary>
        /// 监听客户端连接
        /// </summary>
        /// <param name="obj"></param>
        private void ListtenClinetConnect(object? obj)
        {
            try
            {
                if (wld_client != null && wld_client.Connected)
                {
                    wld_client.Close();
                }
                wld_client = wld_socket.Accept();
                wld_client.SendBufferSize = 8 * 1024 * 1024;
                if (wld_Client_Connected != null)
                    wld_Client_Connected(wld_client.RemoteEndPoint.ToString());
                //wld_client.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));
                //Thread thread = new Thread(ReceiveMessage);
                //thread.Start(wld_client);
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
        }
        /// <summary>
        /// 接收客户端消息
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ReceiveMessage(object? obj)
        {
            Socket clientSocket = (Socket)obj;
            while (true)
            {
                try
                {
                    //获取从客户端发来的数据
                    int length = clientSocket.Receive(wld_recv_buf);
                    Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(wld_recv_buf, 0, length));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
        }
        /// <summary>
        /// 关闭服务
        /// </summary>
        public void Close()
        {
            try
            {
                wld_client?.Close();
                wld_socket?.Close();
                wld_client = null;
                wld_socket = null;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
    }
}
